package com.appheader.rongmaphone.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.appheader.rongmaphone.R;
import com.appheader.rongmaphone.activity.ContentActivity;
import com.appheader.rongmaphone.activity.DialogActivity;
import com.appheader.rongmaphone.adapter.CloudAdapter;
import com.appheader.rongmaphone.cache.file.ResourceFileManager;
import com.appheader.rongmaphone.cache.preference.PreferenceUtil;
import com.appheader.rongmaphone.constants.GlobalVars;
import com.appheader.rongmaphone.entity.CloudEntity;
import com.appheader.rongmaphone.entity.Pages;
import com.appheader.rongmaphone.entity.Project;
import com.appheader.rongmaphone.entity.ProjectEntity;
import com.appheader.rongmaphone.serializable.SerizlizeableMap;
import com.appheader.rongmaphone.user.UserInfo;
import com.appheader.rongmaphone.utils.CompressFile;
import com.appheader.rongmaphone.utils.FileUtil;
import com.appheader.rongmaphone.utils.MD5;
import com.appheader.rongmaphone.utils.json.JSONUtil;
import com.appheader.rongmaphone.utils.network.DownloadUtil;
import com.appheader.rongmaphone.utils.network.HttpUtil;
import com.appheader.rongmaphone.views.RoundProgressBar;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * 云方案的
 */
public class CloudFragment extends Fragment implements AdapterView.OnItemClickListener {

    private static final Integer NEED_DOWNLOAD = 9999;
    private PullToRefreshGridView cloudGridview;
    private DisplayImageOptions options;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    CloudFragment cloudFragment;
    private CloudAdapter adapter;
    public List<CloudEntity> data = new ArrayList<>();
    private RoundProgressBar roundProgressBar;
    private int progress = 0;
    private int pageNum = 1;//加载的页数
    private PreferenceUtil preferenceUtil;
    private static Map<Integer, String> map = new HashMap<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    List<CloudEntity> dataList = (List<CloudEntity>) msg.obj;
//                    int projectNum = (int) msg.obj;
                    data.addAll(dataList);
                    adapter = new CloudAdapter(data, getContext(), options, imageLoader, cloudGridview);
                    cloudGridview.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    cloudGridview.onRefreshComplete();
                    break;
            }
        }
    };
    private String uid;
    private String fileMD5;
    private String time;

    public CloudFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_cloud, container, false);
        cloudGridview = (PullToRefreshGridView) view.findViewById(R.id.cloud_gridview);
        cloudGridview.getRefreshableView().setNumColumns(2);//显示两列
        cloudGridview.setMode(PullToRefreshBase.Mode.BOTH);//同时支持上拉加载，下拉刷新
        roundProgressBar = (RoundProgressBar) view.findViewById(R.id.roundProgress);
        //.cacheInMemory(true)存在内存中
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.default_img)
                .showImageForEmptyUri(R.mipmap.default_img)
                .showImageOnFail(R.mipmap.default_img)
                .cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        preferenceUtil = new PreferenceUtil(getActivity());
        getData();
        cloudGridview.onRefreshComplete();
        cloudGridview.setOnItemClickListener(this);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRefreshGridViewListener();
//        refreshClick();//调用刷新方法
    }

//    private void refreshClick() {
//        Bundle arguments = getArguments();
//        boolean isPressed = arguments.getBoolean("isPressed", false);
//        if (isPressed == true) {
////            Log.e("PRESSED", "onActivityCreated: -------------------" + isPressed);
//            data.clear();
//            getData();
//            cloudGridview.setAdapter(adapter);
//            adapter.notifyDataSetChanged();
//        }
//
//    }

    private void setRefreshGridViewListener() {

        cloudGridview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            //下拉加载
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                data.clear();
                getData();
            }
            //上拉下载
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
//                pageNum++;

               int projectNum =  data.size();
                if (projectNum<=8){
                    cloudGridview.getLoadingLayoutProxy(false,true).setLastUpdatedLabel("没有更多数据");
                    cloudGridview.getLoadingLayoutProxy(false,true).setRefreshingLabel("没有更多数据");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    cloudGridview.onRefreshComplete();
                }else {
                    cloudGridview.getLoadingLayoutProxy(false,true).setLastUpdatedLabel("上拉加载");
                    cloudGridview.onRefreshComplete();
                }

            }
        });
    }

    private void getData() {

        HttpUtil.getCloudOkHttpClient(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String userStr = preferenceUtil.getString("userStr");//从私有目录取出
                UserInfo userInfo = JSONUtil.userInfos(userStr);
                uid = userInfo.getUid();
                //王侃/UID: 577b96e8e182da1b723a1936
                //我的/UID：57f9a48ae182da4aa10a87f3
                Log.e("UID", "onResponse: " + uid);
//                sessionId = userInfo.getSessionId();
//                //刚加载就创建方案目录
                String path = ResourceFileManager.createOrGetUserProfileDir(uid) + File.separator + "previewZip.zip";
//                Log.e("TAG", "onResponse: ------------" + path);
                File file = new File(path);
                if (!file.exists()) {
                    fileMD5 = "";
                }else {
                    fileMD5 = MD5.getFileMD5(file);
                }
//                //生成md5文件成功
//                fileMD5 = MD5.getFileMD5(file);
//                Log.e("MD5", "onResponse: " + fileMD5);
                String string = response.body().string();//返回json字符串获取sessionId，并存到缓存

                preferenceUtil.putString("userList", string);
//                preferenceUtil.putInt("projectNum",);
                Log.e("TAG", "cloudFragment: " + string);
//                if (!TextUtils.isEmpty(string)) {
                List<CloudEntity> cloudEntities = JSONUtil.getCloudInfos(string);
//              Collections.reverse(cloudEntities);//倒序排序
                Message message = Message.obtain();
                message.obj = cloudEntities;
                message.what = 1;
                handler.sendMessage(message);
//                }

            }
        });
    }

    //gridview的item点击监听
    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        //正常是点击，请求网络下载zip包到本地，跳转到详情页，在详情页解压zip包获取信息
        //判断如果下载成功，跳转到详情页，否者提示下载失败！
        //TODO 判断本地zip包是否存在，如果不存在就请求网络下载
        final String projectId = data.get(position).getId();
        String lastModifyTime = data.get(position).getLastModifyTime();

        String picId = data.get(position).getPicId();
        String name = data.get(position).getName();
        String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator
                + GlobalVars.getPackageInfo().packageName
                + "/download"
                + File.separator + uid + "/" + projectId + "/" + projectId + ".json";
        //2016-10-25 10:16:36
        Log.e("CloudFragment", "onItemClick: " + projectId + "-----" + lastModifyTime + "----" + picId);
        File file = new File(sdcardRoot);
        if (!file.exists()) {
            time = "";
        }else {
            String readFile = FileUtil.readFile(sdcardRoot);
            Log.e("readFile", "onItemClick: "+readFile);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(readFile);
                JSONObject jsonObject2 = jsonObject.getJSONObject("project");
                String lastModifyT = jsonObject2.getString("lastModifyTime");
                time = lastModifyT;
                Log.e("readFile", "lastModify: "+lastModifyT+"---"+time);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        HttpUtil.getCloudContentOkHttpClient(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取到详情josn数据（图片资源,音频，视频，needDownload,）
                String result = response.body().string();
                Log.e("RESPONSE", "onResponse: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    String jsonStr = jsonObject1.toString();
                    Boolean needDownload = jsonObject1.getBoolean("needDownload");
                    ProjectEntity.DataEntity projectEntity = new ProjectEntity.DataEntity();
                    projectEntity.setNeedDownload(needDownload);
//                  Log.e("jsonStr", "onResponse: " + jsonStr);Log.e("NEED", "needDownload" + needDownload);
                    preferenceUtil.putBoolean("needDownload"+position, needDownload);
                    JSONArray resList = jsonObject1.getJSONArray("resList");
                    JSONObject jsonObject2 = jsonObject1.getJSONObject("project");
                    Log.e("reslist", "onResponse: " + resList.length());
                    preferenceUtil.putString(projectId+position+"project", jsonObject2.toString());
                    preferenceUtil.putInt(projectId+position+"reslist", resList.length());

                    Log.e("JSONoJECT", "onResponse: " + jsonObject2.toString());
                    Boolean needDown = preferenceUtil.getBoolean("needDownload"+position);
                    Log.e("needDownload", "onItemClick: " + needDownload + "==="+resList+"==" + "--");
                    //okhttp发送get请求下载zip包成功
                    if (needDown) {
                        zipDownload();
                    }
                    //只有project不为空才解析json数据
                    if (jsonObject2 != null || resList.length() != 0) {
                        Map<Integer, String> map1 = new HashMap<Integer, String>();
                        for (int i = 0; i < resList.length(); i++) {
                            String aa = resList.getString(i);
                            Log.e("iiiiii", "onResponse: " + aa);
                            map1.put(i, aa);
                        }
                        map.putAll(map1);

                        Project project = new Project();
                        String projectId = jsonObject2.getString("id");
                        String creator = jsonObject2.getString("creator");
                        String lastModifyTime1 = jsonObject2.getString("lastModifyTime");
                        String pageType = jsonObject2.getString("pageType");
                        project.setPrjectId(projectId);
                        project.setLastModifyTime(lastModifyTime1);
                        project.setPageType(pageType);
                        project.setCreator(creator);
                        Log.e("PROJECT", "onResponse: " + projectId + "---" + creator + "----" + lastModifyTime1 + "-----" + pageType);

                        JSONArray publish = jsonObject2.getJSONArray("publish");
                        for (int i = 0; i < publish.length(); i++) {
                            JSONObject jsonObject3 = publish.getJSONObject(i);
                            int index = jsonObject3.getInt("index");
                            JSONArray pages = jsonObject3.getJSONArray("pages");
                            for (int j = 0; j < pages.length(); j++) {
                                Pages entity = new Pages();
                                JSONObject jsonObject4 = pages.getJSONObject(j);
                                String pageId = jsonObject4.getString("id");
                                int pageIndex = jsonObject4.getInt("index");
                                String thumb = jsonObject4.getString("thumb");
                                List<Pages> pagesList = DataSupport.findAll(Pages.class, 1);
//                                Log.e("PA5GE---", "onResponse: " + pageId + "----" + pageIndex + "---" + thumb);
//                                list.add(entity);
                            }
//                            List<Publish> publish1 = project.getPublish();
//                            publish1.add(publishEntity);
                        }
                        //存储方案的json文件,成功
                        String jsonPath = ResourceFileManager.createOrGetUserProfileDir(uid) + File.separator + projectId;

                        File file = new File(jsonPath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        File filePath = new File(jsonPath + "/" + projectId + ".json");
                        if (!filePath.exists()) {
                            filePath.createNewFile();
                            FileOutputStream fos = new FileOutputStream(filePath);
                            fos.write(jsonStr.getBytes());
                            fos.close();
                        }
                    } else {
                        Toast.makeText(getContext(), "没有数据", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, projectId, fileMD5,time);
        String project = preferenceUtil.getString(projectId+position+"project");
        int resList = preferenceUtil.getInt(projectId+position+"reslist");//取出的是上一次的值
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //再睡一秒
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!project.equals("{}") && resList != 0) {
            //弹出下载ActivityDialog
//            Log.e("TAGmAP", "onItemClick:=========== " + map.size());
            Intent intent = new Intent(getContext(), DialogActivity.class);
            SerizlizeableMap myMap = new SerizlizeableMap();
            myMap.setMap(map);
            Bundle bundle = new Bundle();
            bundle.putSerializable("map", myMap);
            intent.putExtras(bundle);
            intent.putExtra("uid", uid);
            intent.putExtra("projectId", projectId);
            intent.putExtra("review", "true");
            intent.putExtra("picId", picId);
            intent.putExtra("name", name);
            getActivity().startActivity(intent);
            map.clear();
        } else if (project.equals("{}")) {
            if (resList == 0) {
                Toast.makeText(getContext(),"没有数据", Toast.LENGTH_SHORT).show();
            } else {
                //跳转到详情页面
                Intent intent = new Intent(getContext(), ContentActivity.class);
                //传递用户id，与方案id过去
                intent.putExtra("uid", uid);
                intent.putExtra("projectId", projectId);
                intent.putExtra("review", "review");
                intent.putExtra("picId", picId);
                intent.putExtra("name", name);
                intent.putExtra("pageType", "phone");
                Log.e("INTENT", "onItemClick: " + projectId);
                startActivity(intent);
            }
        }
        //下载每页的json文件到本地
        DownloadUtil.pageJsonDownLoad(uid, sdcardRoot, projectId);
    }

    private void zipDownload() {

            HttpUtil.getZipOkHttpClient(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    int downLoadFileSize = 0;
                    String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + GlobalVars.getPackageInfo().packageName + "/download" + File.separator + uid;
//                    Log.e("TAG", "onResponse:++++++++++++++++ " + sdcardRoot);
                    File rootDir = new File(sdcardRoot);
                    //创建目录
                    if (!rootDir.exists()) {
                        boolean is = rootDir.mkdirs();
//                        Log.e("IS", "onResponse: ---" + is);
                    }
//                //下载后的文件名
                    String filePath = sdcardRoot + File.separator + "previewZip.zip";
                    File file = new File(filePath);
                    if (file.exists()) {
                        file.delete();
                    }
                    InputStream inputStream = response.body().byteStream();
                    long total = response.body().contentLength();
//                    Log.e("TOTAL", "onResponse: " + total);
                    long sum = 0;
                    int len = 0;
                    byte[] buf = new byte[2048];
                    FileOutputStream fos = new FileOutputStream(filePath);
                    while ((len = inputStream.read(buf)) != -1) {
                        downLoadFileSize += len;
                        fos.write(buf, 0, len);
                        Log.e("zipdonwload", "downloadFile: " + downLoadFileSize);
                        fos.flush();
                    }
                    inputStream.close();
                    fos.close();
                    //解压
                    CompressFile.unZipFileAndOpenNewPage(uid);
                }
            });

    }
}
